const config = require("./config.json")
const ws = require("nodejs-websocket")
const EventEmitter = require('events') 

const core = require('./watcher')

ws.createServer(conn=>{
	if(!conn.$){
		conn.$={
			channel:[],
			event:new EventEmitter(),
			interval:setInterval(()=>{
				(async()=>{
					await core.getData(conn) 
				
				})()
			},1000),
			msgMap :new Map()
		}
		conn.$.event.on('received',(chn,msg)=>{
			conn.sendText(chn.concat(" ").concat(msg))
		})
	}
	conn.on("text",  msg=>{
		(async()=>{
			let result = await core.core(conn,msg) 
			conn.sendText(result)
		})()
	});
	conn.on('close',()=>{
		//释放资源
		clearInterval(conn.$.interval)
		conn.$ = null
	});
}).listen(config.server.port)